import axios, { AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API_URL as string,
    timeout: 15000,
    withCredentials: false, // 不携带跨域Cookie，除非服务端特别配置
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        // 从本地获取token并添加到请求头
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        
        return config;
    },
    (error) => {
        console.error('请求错误:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        // 直接返回响应数据，不再包装成AxiosResponse
        return response.data;
    },
    (error) => {
        console.error('响应错误:', error);
        let message = '请求失败';
        
        if (error.response) {
            // 服务器返回了错误状态码
            const status = error.response.status;
            const data = error.response.data;
            
            switch (status) {
                case 400:
                    message = '请求错误';
                    break;
                case 401:
                    message = '未授权，请重新登录';
                    break;
                case 403:
                    message = '无权限访问';
                    break;
                case 404:
                    message = '请求的资源不存在';
                    break;
                case 500:
                    message = '服务器错误';
                    break;
                default:
                    message = `未知错误 (${status})`;
            }
            
            // 如果服务器返回了错误信息，优先使用服务器的错误信息
            if (data && data.message) {
                message = data.message;
            }
        } else if (error.message) {
            if (error.message.includes('timeout')) {
                message = '请求超时';
            } else if (error.message.includes('Network Error')) {
                message = '网络错误，请检查您的网络连接';
            } else {
                message = error.message;
            }
        }
        
        ElMessage.error(message);
        return Promise.reject(error);
    }
);

// 封装请求方法
const request = {
    // GET 请求
    get<T = any>(url: string, params?: any, config?: any): Promise<T> {
        const mergedConfig = { params, ...config };
        return service.get(url, mergedConfig);
    },
    
    // POST 请求
    post<T = any>(url: string, data?: any, config?: any): Promise<T> {
        return service.post(url, data, config);
    },
    
    // PUT 请求
    put<T = any>(url: string, data?: any, config?: any): Promise<T> {
        return service.put(url, data, config);
    },
    
    // DELETE 请求
    delete<T = any>(url: string, config?: any): Promise<T> {
        return service.delete(url, config);
    },
    
    // 上传文件
    upload<T = any>(url: string, file: File, name: string = 'file', data?: Record<string, any>, config?: any): Promise<T> {
        const formData = new FormData();
        formData.append(name, file);
        
        if (data) {
            Object.keys(data).forEach(key => {
                formData.append(key, data[key]);
            });
        }
        
        return service.post(url, formData, {
            ...config,
            headers: {
                'Content-Type': 'multipart/form-data',
                ...(config?.headers || {})
            }
        });
    },
    
    // 下载文件
    download(url: string, params?: any, config?: any): Promise<Blob> {
        return service.get(url, {
            ...config,
            params,
            responseType: 'blob'
        });
    }
};

export default request;
